﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Print.Domain;


namespace Mengsk.ProxyDelivery.Print.UI
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class PrintTestWindow : Window
    {
        public PrintTemplate PrintTemplate { get; set; }

        public PrintTestWindow()
        {
            InitializeComponent();
        }

        private Thumb[] CreateThumbFrom(PrintTemplateItem[] items)
        {
            Thumb[] thumbs = new Thumb[items.Length];

            for (int i = 0; i < thumbs.Length; i++)
            {
                thumbs[i] = new Thumb { DataContext = items[i] };
                thumbs[i].Style = this.FindResource("ThumbStyle") as Style;
                Canvas.SetTop(thumbs[i], items[i].Y + PrintTemplate.YOffset);
                Canvas.SetLeft(thumbs[i], items[i].X + PrintTemplate.XOffset);
                Canvas.SetZIndex(thumbs[i], i + 1);
                thumbs[i].Width = items[i].Width;
                thumbs[i].Height = items[i].Height;
                thumbs[i].FontSize = items[i].FontSize;
                thumbs[i].FontFamily = new System.Windows.Media.FontFamily(items[i].FontName);
            }
            return thumbs;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.c1.Width = PrintTemplate.Width;
            this.c1.Height = PrintTemplate.Height;
            var items = CreateThumbFrom(PrintTemplate.Items.ToArray());
            foreach (var item in items)
            {
                this.c1.Children.Add(item);
            }
            this.Dispatcher.BeginInvoke(new Action(() => this.c1_Click(null, null)));
        }

        private void c1_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog pd = new PrintDialog();
            if (pd.ShowDialog().Value == false)
            {
                return;
            }

            try
            {
                pd.PrintVisual(this.c1, "测试打印");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void c1_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                return;
            }
            e.Handled = true;
            c1_Click(null, null);
        }
    }
}
